package main

import (
	"encoding/json"
	"gitee.com/pdudo/SampleHttp"
	"strings"
	"time"
)

// 记录表
type IndexNode struct {
	Title string // 标题
	Node string // 内容
	UpTime time.Time // 时间
}

// demo存放的地方
var IndexNodes []IndexNode

// 新增记录
func AddIndex(info *SampleHttp.HttpInfo) {
	title := info.RequestInfo.RequestData["title"] // 获取上传上来的标题
	val := info.RequestInfo.RequestData["node"] // 获取上传上来的内容

	// 如果上传上来数据不对,则返回 400
	if title == "" || val == "" {
		info.SetHttpStatusCode(400)
		info.Write([]byte("上传数据有误"))
		return
	}

	// 申请一个IndexNode存放数据
	var newNode IndexNode
	newNode.Title = title
	newNode.Node = val
	newNode.UpTime = time.Now()

	// 添加到留言数组中去
	IndexNodes = append(IndexNodes, newNode)

	info.SetHttpStatusCode(200)
	info.Write([]byte(title+"已经提交成功!"))
}

// 查询全部记录
func QueryAll(info *SampleHttp.HttpInfo) {
	buf , err := json.Marshal(&IndexNodes)
	if err != nil {
		info.SetHttpStatusCode(500)
		info.Write([]byte("服务器出错！"))
		return
	}

	info.Write(buf)
}

// 查询单条记录
func QueryOne(info *SampleHttp.HttpInfo) {
	keys := info.RequestInfo.RequestData["key"]

	if "" == keys {
		info.SetHttpStatusCode(400)
		info.Write([]byte("上传数据有误！"))
		return
	}


	var searchIndexNodes []IndexNode
	for _,v := range IndexNodes {
		if strings.Contains(v.Title,keys) || strings.Contains(v.Node,keys) {
			searchIndexNodes = append(searchIndexNodes, v)
		}
	}

	buf , err := json.Marshal(&searchIndexNodes)
	if err != nil {
		info.SetHttpStatusCode(500)
		info.Write([]byte("服务器出错！"))
		return
	}
	info.Write(buf)
}


func main() {
	SampleHttp.Route("post","/addIndex",AddIndex) // 新增记录 路由
	SampleHttp.Route("get","/queryAll",QueryAll) // 新增全部记录 路由
	SampleHttp.Route("get","/queryOne",QueryOne) // 查询单条记录 路由
	SampleHttp.StartServer("0.0.0.0:8082")
}
